package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.listener.ExcelListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public List<Category> findCategoryByParentId(Long id) {
        List<Category> categoryList = categoryMapper.findCategoryByParentId(id);
        if(!CollectionUtils.isEmpty(categoryList)) {
            //处理查询的分类，设置当前分类是否含有子分类。给hasChildren属性赋值
            categoryList.forEach((category) -> {
                int count = categoryMapper.countByParentId(category.getId());
                if (count > 0) {
                    category.setHasChildren(true);
                } else {
                    category.setHasChildren(false);
                }
            });
        }
        return categoryList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //1.设置响应内容类型。服务器端告诉客户端返回的数据类型和字符编码。
            response.setContentType("application/vnd.ms-excel");  //   application/json     text/html     image/jpeg
            response.setCharacterEncoding("UTF-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //2.查询所有分类 List<Category>
            List<Category> categoryList = categoryMapper.findAll();

            //3.数据类型转换 List<Category> -> List<CategoryExcelVo>
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>();
            categoryList.forEach(category -> {
                CategoryExcelVo vo = new CategoryExcelVo();
                BeanUtils.copyProperties(category,vo);
                categoryExcelVoList.add(vo);
            });

            //4.进行Excel写操作。输出流不是本地文件流，而是响应流
            EasyExcel.write(response.getOutputStream(),CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void importData(MultipartFile file) {
        try {

            //在构造监听器对象时，需要传递dao对象，进行数据库操作
            ExcelListener<CategoryExcelVo> excelListener = new ExcelListener(categoryMapper);
            //通过文件获取输入流，excel数据。批量写入数据库
            EasyExcel.read(file.getInputStream(), CategoryExcelVo.class, excelListener).sheet().doRead();

        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
